#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from email.mime import image
import os,sys
from unittest import runner
from django.contrib.auth.models import User, Group, Permission
from django.utils.timezone import now
from PIL import Image

import users
from .models import *
from rest_framework import mixins
from rest_framework import serializers
from rest_framework.serializers import *



class GroupOptionSerializer(serializers.ModelSerializer):
    """
    用户分组序列化器
    """
    # user_names = serializers.SerializerMethodField()
    # permission_auth = serializers.SerializerMethodField()
    # permission_patrol = serializers.SerializerMethodField()
    class Meta:
        model = Group
        fields = ['id', 'name']


class GroupSerializer(serializers.ModelSerializer):
    """
    用户分组序列化器
    """
    user_names = serializers.SerializerMethodField()
    permission_auth = serializers.SerializerMethodField()
    out_group_users = serializers.SerializerMethodField()

    class Meta:
        model = Group
        fields = ['id', 'name', 'user_set', 'out_group_users', 'user_names',
                  'permission_auth']

    def get_out_group_users(self, obj):
        in_group_users = obj.user_set.all()
        out_group_users = User.objects.exclude(
            id__in=in_group_users).values_list('id', flat=True)
        return out_group_users

    def get_permission_auth(self, obj):
        permission_auth = []
        for permission in obj.permissions.filter(content_type__app_label__exact='auth'):
            permission_auth.append(permission.pk)
        return permission_auth

    def get_user_names(self, obj):
        user_names = ''
        users = obj.user_set.all()
        for user in users:
            user_names += user.extension.name + ','
        return user_names

# 用户序列化器
class UserSerializer(serializers.ModelSerializer):
    """
    用户序列化器
    """
    # 序列化处理方法，用来获取对应字段对应外键的其他内容，比如用户id的用户名
    name = serializers.CharField(source='extension.name', read_only=True)
    grade = serializers.CharField(source='extension.grade', read_only=True)
    role = serializers.CharField(source='extension.role', read_only=True)
    sex_num = serializers.CharField(source='extension.sex', read_only=True)
    # sex = serializers.SerializerMethodField()
    groups = serializers.SerializerMethodField()
    course = serializers.SerializerMethodField()
    homework = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = "__all__"

    # # 编写想要自定义的序列化处理方法
    # def get_sex(self, obj):
    #     if obj.sex_num == '0':
    #         return '男'
    #     elif obj.sex_num == '1':
    #         return '女'
    #     else:
    #         return '未知'
    def get_homework(self,obj):
        homeworks = []
        for homework in HomeworkCheckTask.objects.filter(runner=obj.id):
            homeworks.append(homework.homework.name)
        return homeworks

    def get_course(self,obj):
        courses = []
        for score in Score.objects.filter(user=obj.id):
            courses.append(score.course.name)
        return courses

    def get_groups(self, obj):
        groups = []
        for group in Group.objects.all():
            if obj in group.user_set.all():
                groups.append(group.id)
        return groups

    def update(self, instance, validated_data):
        '''序列化器重写修改实例'''
        user_info = self.context['request'].data
        print('**********************************')
        print(user_info)
        if 'password' in validated_data:
            instance.set_password(validated_data["password"])
            instance.extension.last_change_date = now()
        instance.save()
        return instance

# 用户下拉列表下拉选
class UserOptionSerializer(serializers.ModelSerializer):
    """
    用户下拉列表下拉选
    """
    value = serializers.CharField(source='username')
    grade = serializers.CharField(source='extension.grade.name', read_only=True)
    role = serializers.CharField(source='extension.role.name', read_only=True)
    label = serializers.CharField(source='extension.name', read_only=True)

    class Meta:
        model = User
        fields = ['value', 'label', 'grade', 'role']

#选课信息序列化器
class ScoreSerializer(serializers.ModelSerializer):

    name = serializers.CharField(source='user.name', read_only=True)
    course = serializers.CharField(source='course.name', read_only=True)
    teacher = serializers.CharField(source='course.createdBy',read_only=True)
    courseType = serializers.CharField(source='course.type',read_only=True)
    courseDesc = serializers.CharField(source='course.desc',read_only=True)
    schoolTime = serializers.DateTimeField(source= 'course.schoolTime',
    required=False, format='%Y-%m-%d %H:%M:%S')
    finishTime = serializers.DateTimeField(source= 'course.finishTime',
    required=False, format='%Y-%m-%d %H:%M:%S')
    class Meta:
        model = Score
        fields = "__all__"

#岗位信息
class RoleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Role
        fields = "__all__"
    
#岗位信息下拉列表下拉选
class RoleOptionSerializer(serializers.ModelSerializer):

    value = serializers.IntegerField(source='id')
    label = serializers.CharField(source='name')

    class Meta:
        model = Role
        fields = ['value', 'label']
    
#班级
class GradeSerializer(serializers.ModelSerializer):

    created_by_name = serializers.CharField(source='createdBy.name', read_only=True)
    users = serializers.SerializerMethodField()

    class Meta:
        model = Grade
        fields = "__all__"
    
    def create(self, validated_data):
        '''序列化器重写创建实例'''
        user = self.context["request"].user
        grade = Grade()
        # 传入参数
        if "name" in validated_data:
            grade.name = validated_data["name"]
        grade.createdBy = user.username
        grade.save()
        grade.save()
        return grade
    
    def update(self, instance, validated_data):
        raise_errors_on_nested_writes('update', self, validated_data)
        info = model_meta.get_field_info(instance)
        user = self.context["request"].user
        if "name" in validated_data:
            instance.name = validated_data["name"]
        instance.save()
        return instance

    def get_users(self,obj):
        users = UserExtension.objects.filter(grade=obj).values_list('name',flat=True)
        return users

#班级下拉列表下拉选
class GradeOptionSerializer(serializers.ModelSerializer):

    value = serializers.IntegerField(source='id')
    label = serializers.CharField(source='name')

    class Meta:
        model = Grade
        fields = ['value', 'label']
    
#课程
class CourseSerializer(serializers.ModelSerializer):
    createdBy = serializers.CharField(source='extension.name', read_only=True)
    schoolTime = serializers.DateTimeField(
        required=False, format='%Y-%m-%d %H:%M:%S')
    finishTime = serializers.DateTimeField(
        required=False, format='%Y-%m-%d %H:%M:%S')

    class Meta:
        model = Course
        fields = "__all__"


    
#课程下拉列表下拉选
class CourseOptionSerializer(serializers.ModelSerializer):

    value = serializers.IntegerField(source='id')
    label = serializers.CharField(source='name')

    class Meta:
        model = Course
        fields = ['value', 'label']
    
#作业
class HomeworkSerializer(serializers.ModelSerializer):

    created_by_name = serializers.CharField(source='createdBy.name', read_only=True)
    createdDate = serializers.DateTimeField(required=False, format='%Y-%m-%d %H:%M:%S')
    student_name = serializers.CharField(source='student.name', read_only=True)
    class Meta:
        model = Homework
        fields = "__all__"
    
#作业下拉列表下拉选
class HomeworkOptionSerializer(serializers.ModelSerializer):

    value = serializers.IntegerField(source='id')
    label = serializers.CharField(source='name')

    class Meta:
        model = Homework
        fields = ['value', 'label']
    
#作业完成结果记录
class HomeworkCheckTaskSerializer(serializers.ModelSerializer):

    homework_name = serializers.CharField(source='homework.name', read_only=True)
    runStartTime = serializers.DateTimeField(required=False, format='%Y-%m-%d %H:%M:%S')
    runEndTime = serializers.DateTimeField(required=False, format='%Y-%m-%d %H:%M:%S')
    runnerName = serializers.CharField(source='runner.name', read_only=True)
    homework_desc = serializers.CharField(source='homework.desc', read_only=True)
    courseType = serializers.CharField(source='homework.desc', read_only=True)
    taskResult = serializers.SerializerMethodField()

    class Meta:
        model = HomeworkCheckTask
        fields = "__all__"

    def get_taskResult(self, obj):
        switcher = {
            'pass': '合格',
            'fail': '不合格',
        }
        return switcher.get(obj.result, '')
    
#作业完成结果记录下拉列表下拉选
class HomeworkCheckTaskOptionSerializer(serializers.ModelSerializer):

    value = serializers.IntegerField(source='id')
    url = serializers.CharField(source='homework.name')

    class Meta:
        model = HomeworkCheckTask
        fields = ['value', 'url']
    
#用户肖像图片
class UserPortraitSerializer(serializers.ModelSerializer):

    user_name = serializers.CharField(source='user.name', read_only=True)
    created_by_name = serializers.CharField(source='createdBy.name', read_only=True)
    createdDate = serializers.DateTimeField(required=False, format='%Y-%m-%d %H:%M:%S')
    last_edited_by_name = serializers.CharField(source='lastEditedBy.name', read_only=True)
    lastEditedDate = serializers.DateTimeField(required=False, format='%Y-%m-%d %H:%M:%S')
    portrait = serializers.CharField(source='portrait.portrait', read_only=True)

    class Meta:
        model = UserPortrait
        fields = "__all__"
    
#用户肖像图片下拉列表下拉选
class UserPortraitOptionSerializer(serializers.ModelSerializer):

    value = serializers.IntegerField(source='id')
    label = serializers.CharField(source='portrait.portrait')

    class Meta:
        model = UserPortrait
        fields = ['value', 'label']
    
#肖像图片
class PortraitSerializer(serializers.ModelSerializer):

    created_by_name = serializers.CharField(source='createdBy.name', read_only=True)
    createdDate = serializers.DateTimeField(required=False, format='%Y-%m-%d %H:%M:%S')
    last_edited_by_name = serializers.CharField(source='lastEditedBy.name', read_only=True)
    lastEditedDate = serializers.DateTimeField(required=False, format='%Y-%m-%d %H:%M:%S')
    portrait = serializers.CharField(read_only=True)

    class Meta:
        model = Portrait
        fields = "__all__"
    
#肖像图片下拉列表下拉选
class PortraitOptionSerializer(serializers.ModelSerializer):

    value = serializers.IntegerField(source='id')
    label = serializers.CharField(source='portrait')

    class Meta:
        model = Portrait
        fields = ['value', 'label']
    
#课堂图片
class ImagesSerializer(serializers.ModelSerializer):

    images_url = serializers.CharField(source='images')
    created_by_name = serializers.CharField(source='createdBy.name', read_only=True)
    createdDate = serializers.DateTimeField(required=False, format='%Y-%m-%d %H:%M:%S')
    last_edited_by_name = serializers.CharField(source='lastEditedBy.name', read_only=True)
    lastEditedDate = serializers.DateTimeField(required=False, format='%Y-%m-%d %H:%M:%S')

    class Meta:
        model = Images
        fields = "__all__"
    
#课堂图片下拉列表下拉选
class ImagesOptionSerializer(serializers.ModelSerializer):

    value = serializers.IntegerField(source='id')
    label = serializers.CharField(source='images')

    class Meta:
        model = Images
        fields = ['value', 'label']
    
#用户学习图片
class UserImageSerializer(serializers.ModelSerializer):

    user_name = serializers.CharField(source='user.name')
    images_url = serializers.CharField(source='image.images')
    created_by_name = serializers.CharField(source='createdBy.name', read_only=True)
    createdDate = serializers.DateTimeField(required=False, format='%Y-%m-%d %H:%M:%S')
    last_edited_by_name = serializers.CharField(source='lastEditedBy.name', read_only=True)
    lastEditedDate = serializers.DateTimeField(required=False, format='%Y-%m-%d %H:%M:%S')

    class Meta:
        model = UserImage
        fields = "__all__"
    
#用户学习图片下拉列表下拉选
class UserImageOptionSerializer(serializers.ModelSerializer):

    value = serializers.IntegerField(source='id')
    label = serializers.CharField(source='user.name')

    class Meta:
        model = UserImage
        fields = ['value', 'label']
    
#文件存储
class FilesSerializer(serializers.ModelSerializer):


    file_url = serializers.CharField(source='fileUrl')
    created_by_name = serializers.CharField(source='createdBy.name', read_only=True)
    createdDate = serializers.DateTimeField(required=False, format='%Y-%m-%d %H:%M:%S')
    last_edited_by_name = serializers.CharField(source='lastEditedBy.name', read_only=True)
    lastEditedDate = serializers.DateTimeField(required=False, format='%Y-%m-%d %H:%M:%S')
    fileType = serializers.SerializerMethodField()

    class Meta:
        model = Files
        fields = "__all__"
    
    def get_fileType(self, obj):
        switcher = {
            'mp4': 'mp4视频',
            'mkv': 'mkv视频',
            'apk': '安装包',
            'pdf': 'pdf文档'
        }
        return switcher.get(obj.fileType, '')

#文件存储下拉列表下拉选
class FilesOptionSerializer(serializers.ModelSerializer):

    value = serializers.IntegerField(source='id')
    label = serializers.CharField(source='title')

    class Meta:
        model = Files
        fields = ['value', 'label']
    
#用户学习文件存储
class UserFileSerializer(serializers.ModelSerializer):

    user_name = serializers.CharField(source='user.name')
    file_url = serializers.CharField(source='file.fileUrl')
    created_by_name = serializers.CharField(source='createdBy.name', read_only=True)
    createdDate = serializers.DateTimeField(required=False, format='%Y-%m-%d %H:%M:%S')
    last_edited_by_name = serializers.CharField(source='lastEditedBy.name', read_only=True)
    lastEditedDate = serializers.DateTimeField(required=False, format='%Y-%m-%d %H:%M:%S')

    class Meta:
        model = UserFile
        fields = "__all__"
    
#用户学习文件存储下拉列表下拉选
class UserFileOptionSerializer(serializers.ModelSerializer):

    value = serializers.IntegerField(source='id')
    name = serializers.CharField(source='user.name')
    title = serializers.CharField(source='file.title')


    class Meta:
        model = UserFile
        fields = ['value', 'name','title']
    
    